package com.token.iot.bratterycharging.gateway;

import com.outstanding.framework.core.Logger;
import com.outstanding.framework.core.PendingException;
import com.outstanding.framework.log.LoggerFactory;
import com.token.iot.bratterycharging.gateway.utils.ByteUtil;

import io.netty.channel.ChannelHandlerContext;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;

public class IMEI {

	private static Logger loger = LoggerFactory.getLogger(IMEI.class);

	private static ChannelHandlerContextManager manager = new ChannelHandlerContextManager();
	static public final AttributeKey<String> attributeIMEI = AttributeKey.valueOf("IMEI");

	/**
	 * 一般是Oper调用
	 * 
	 * @param ctx
	 * @return
	 * @throws PendingException
	 */
	public static String getIMEIEnableNull(ChannelHandlerContext ctx) {
		Attribute<String> attr = ctx.channel().attr(attributeIMEI);
		String imei = null;
		if (attr != null) {
			imei = attr.get();
			return imei;
		}
		return null;
	}

	/**
	 * 一般是Oper调用
	 * 
	 * @param ctx
	 * @return
	 * @throws PendingException
	 */
	public static String getIMEI(ChannelHandlerContext ctx) throws PendingException {
		Attribute<String> attr = ctx.channel().attr(attributeIMEI);
		String imei = null;
		if (attr != null) {
			imei = attr.get();
			if (imei == null) {
				throw new PendingException(ResCode.IMEIISNULL);
			}
			if (manager.getChannelHandlerContextByImei(imei) == null) {
				manager.putIfAbsent(imei, ctx);
			}
			//loger.info(" the ChannelHandlerContext's IMEI=" + imei);
			return imei;
		}
		throw new PendingException(ResCode.IMEIISNULL);

	}
}
